from google.appengine.ext import db
import time
print 'Content-Type: text/plain'
print ''
print 'Database Demo: %s' % time.asctime()


class Student(db.Model):
  name = db.StringProperty(required=True)
  home_state = db.StringProperty(required=True)
  birthday = db.StringProperty(required=False)
  ts = db.DateTimeProperty(auto_now_add=True)

def CreateStudent(name, home_state, birthday=None):
  print 'Creating student: %s' %(name)
  student = Student(name=name, home_state=home_state, birthday=birthday)
  student.put()

def GetAllStudents():
  return Student.all()
  
def PrintStudents(query):
  print 'Name\t\tHome\t\tBirthday\t\tDate_added'
  for r in query:
    print '%s\t\t%s\t\t%s\t\t%s' %(r.name, r.home_state, r.birthday, r.ts)


def PrintAllStudents():
  print 'Listing all students in the Datastore'
  query = GetAllStudents()
  PrintStudents(query)

def FindStudentsInState(state):
  query = Student.all()
  query.filter("home_state =", state)
  return query

def ResetStudents():
  print 'Resetting Students'
  query = Student.all()
  if query:
    for r in query:
      r.delete()
  print ''

def MoveStudents(from_state, to_state):
  print 'Moving all students from: %s to %s' %(from_state, to_state)
  query = Student.all()
  query.filter("home_state =", from_state)
  for r in query:
    r.home_state = to_state
    r.put()

def birth(to_birthday):
  print 'Changing all student\'s birthdays.'
  query = Student.all()
  for r in query:
    r.birthday = to_birthday
    r.put()

def GetNStudents(n=10):
  print 'Getting first %s students' %(n)
  query = Student.all()
  return query.fetch(n)

def GetStudentRange(limit=1, offset=1):
  print 'Getting %d students from position %d' %(limit, offset)
  query = Student.all()
  return query.fetch(limit=limit, offset=offset)
    

print ''
ResetStudents()
CreateStudent('Mike', 'Nevada', '01-01-1980')
CreateStudent('Amy', 'California')
CreateStudent('Larry', 'California')
CreateStudent('Sarah', 'New York')
print ''
PrintAllStudents()
print ''
print 'Now finding students in California'
PrintStudents(FindStudentsInState('California'))
print ''
MoveStudents('California', 'Oregon')
print ''
birth('today')
print ''
PrintAllStudents()
print ''
PrintStudents(GetNStudents(2))

print ''
PrintStudents(GetStudentRange(2,1))
